package com.example.cc.mygit.view.issue;

import com.example.cc.mygit.GitApplication;
import com.example.cc.mygit.model.Issue;
import com.example.cc.mygit.model.Project;
import com.example.cc.mygit.model.User;
import com.example.cc.mygit.source.API;
import com.haibin.elegant.Response;
import com.haibin.elegant.call.CallBack;

import java.util.List;

/**
 * Created by cc on 2017/1/1.
 */

public class IssuePresenter implements IssueContract.Presenter{

    private final IssueContract.View mView;
    private Project mProject;
    private User mUser;
    private int mPage = 1;

    public IssuePresenter(IssueContract.View mView, Project mProject) {
        this.mView = mView;
        this.mProject = mProject;
        mUser = GitApplication.getConfig().getUser();
        this.mView.setPresenter(this);
    }
    @Override
    public void onRefreshing() {
        API.getIssues(mProject.getId(),
                mUser.getPrivateToken(),
                1,
                new CallBack<List<Issue>>() {
                    @Override
                    public void onResponse(Response<List<Issue>> response) {
                        List<Issue> issues = response.getBody();
                        if (issues != null) {
                            mPage = 2;
                            mView.onRefreshSuccess(issues);
                            if (issues.size() < 20) {
                                mView.showNoMoreData();
                            }
                        }
                        mView.onComplete();
                    }

                    @Override
                    public void onFailure(Exception e) {
                        mView.onComplete();
                    }
                });
    }

    @Override
    public void onLoadMore() {
        API.getIssues(mProject.getId(),
                mUser.getPrivateToken(),
                mPage,
                new CallBack<List<Issue>>() {
                    @Override
                    public void onResponse(Response<List<Issue>> response) {
                        List<Issue> issues = response.getBody();
                        if (issues != null) {
                            ++mPage;
                            mView.onLoadMoreSuccess(issues);
                            if (issues.size() < 20) {
                                mView.showNoMoreData();
                            }
                        }
                        mView.onComplete();
                    }

                    @Override
                    public void onFailure(Exception e) {
                        mView.onComplete();
                    }
                });

    }

    @Override
    public void start() {

    }
}
